package cn.com.xyc.action;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;

import cn.com.xyc.common.ALiYunTool;
import cn.com.xyc.common.FileManageTool;
import cn.com.xyc.common.QrCodeUtil;

public class QrCodeAction extends BaseAction {
	private Map<String, String> publicMap;
	private Map<String, Object> jsonMap;

	private static int WIDTH = 200;
	private static int HEIGHT = 200;

	public String makeQrCodeInit() {
		return "makeQrCodeInit";
	}

	public String makeQrCode() {
		try {
			String result = makeZXCode(publicMap.get("qrCodeLogo"),
					publicMap.get("qrCodeContent"));
			jsonMap = new HashMap<String, Object>();
			jsonMap.put("result", result);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "ajaxReturn";
	}

	private HttpPost setRequestParams(Map<String, String> params, HttpPost post)
			throws UnsupportedEncodingException {
		List<NameValuePair> paramList = new ArrayList<NameValuePair>();
		Set<Entry<String, String>> paramsEntry = params.entrySet();
		for (Entry<String, String> entry : paramsEntry) {
			paramList.add(new BasicNameValuePair(entry.getKey(), entry
					.getValue()));
		}
		HttpEntity paramEntity = new UrlEncodedFormEntity(paramList, HTTP.UTF_8);
		post.setEntity(paramEntity);
		return post;
	}

	public String makeZXCode(String logoAddress, String content) {
		File logoImage = FileManageTool.FileDown(logoAddress);
		File qrCode = QrCodeUtil.encodeQRCodeImage(content, "UTF-8", WIDTH,
				HEIGHT, logoImage);
		String uploadPath = "qrCode/" + System.currentTimeMillis()
				+ qrCode.getName().substring(qrCode.getName().lastIndexOf("."));
		String url = null;
		try {
			url = ALiYunTool.uploadGroupIcon(qrCode, "picdata", uploadPath);
            logoImage.delete();
            qrCode.delete();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}

		return url;
	}

	public Map<String, String> getPublicMap() {
		return publicMap;
	}

	public void setPublicMap(Map<String, String> publicMap) {
		this.publicMap = publicMap;
	}

	public Map<String, Object> getJsonMap() {
		return jsonMap;
	}

	public void setJsonMap(Map<String, Object> jsonMap) {
		this.jsonMap = jsonMap;
	}

}
